package cn.xd.base.application.service.query.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.xd.base.application.assembler.AdminMenuAssembler;
import cn.xd.base.application.dto.query.AdminMenuQuery;
import cn.xd.base.application.service.query.AdminMenuQueryAppService;
import cn.xd.base.domain.bean.response.AdminMenuDTO;
import cn.xd.base.domain.bean.response.JsonAdminMenuTree;
import cn.xd.base.persistence.dos.AdminMenuDO;
import cn.xd.base.persistence.mps.AdminMenuMpService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminMenuQueryAppServiceImpl implements AdminMenuQueryAppService {

    @Resource
    private AdminMenuMpService adminMenuMpService;

    /**
     * 获取菜单
     *
     * @param adminMenuQuery
     * @return 字典分页
     */
    @Override
    public List<AdminMenuDTO> getAdminMenuList(AdminMenuQuery adminMenuQuery) {
        return (List<AdminMenuDTO>) adminMenuMpService.getList(Wrappers.lambdaQuery(AdminMenuDO.class)
                .eq(ObjUtil.isNotNull(adminMenuQuery.getParentId()), AdminMenuDO::getParentId, adminMenuQuery.getParentId())
                .in(CollUtil.isNotEmpty(adminMenuQuery.getPerms()), AdminMenuDO::getPerms, adminMenuQuery.getPerms())
                .orderByDesc(AdminMenuDO::getOrderNum), AdminMenuAssembler.INSTANCE).get();
    }

    @Override
    public List<JsonAdminMenuTree> getAdminMenuJsonTree(Long parentId, List<String> perms) {
        List<JsonAdminMenuTree> trees = new ArrayList<>();
        AdminMenuQuery adminMenuQuery = new AdminMenuQuery();
        adminMenuQuery.setParentId(parentId);
        adminMenuQuery.setPerms(perms);
        List<AdminMenuDTO> adminMenuList = this.getAdminMenuList(adminMenuQuery);
        for (AdminMenuDTO adminMenuDTO : adminMenuList) {
            JsonAdminMenuTree jsonAdminMenuTree = new JsonAdminMenuTree(adminMenuDTO);
            List<JsonAdminMenuTree> labelListForJson = this.getAdminMenuJsonTree(adminMenuDTO.getId(), perms);
            if (CollectionUtils.isEmpty(labelListForJson)) {
                jsonAdminMenuTree.setChildren(null);
            } else {
                jsonAdminMenuTree.setChildren(labelListForJson);
            }
            trees.add(jsonAdminMenuTree);
        }
        return trees;
    }
}
